package cn.tedu.jxdm.service.impl;

import cn.tedu.jxdm.ex.ServiceException;
import cn.tedu.jxdm.mapper.UserMapper;
import cn.tedu.jxdm.pojo.dto.UserRegDTO;
import cn.tedu.jxdm.pojo.entity.User;
import cn.tedu.jxdm.pojo.vo.UserVO;
import cn.tedu.jxdm.service.IUserService;
import cn.tedu.jxdm.web.ServiceCode;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserVO selectByUserName(String username){
        UserVO queryResult=userMapper.selectByUserName(username);
        if (queryResult == null){
            String message="登录失败，用户名不存在！";
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }

        return queryResult;
    }

    @Override
    public UserVO selectByPassword(String password){
        UserVO queryResult=userMapper.selectByPassword(password);
        if (queryResult==null){
            String message="登录失败，密码错误!";
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }

        return queryResult;
    }

    @Override
    public void insert(UserRegDTO userRegDTO) {
        String name= userRegDTO.getUsername();
        int countByName= userMapper.countByName(name);

        if (countByName>0){
            String message="创建用户失败，用户名已存在！";
            throw new ServiceException(ServiceCode.ERR_CONFLICT,message);
        }

        User user=new User();
        BeanUtils.copyProperties(userRegDTO,user);
        int rows=userMapper.insert(user);
        if (rows !=1){
            String message="添加用户失败，服务器忙，稍后再尝试!";
            throw new ServiceException(ServiceCode.ERR_INSERT,message);
        }
    }
}
